package com.wang.myapplication.tools;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.wang.myapplication.base.MyApp;

import java.util.Set;


/**
 * Created by xhwang on 2018/4/20.
 */

public class SharedPreTool {

    public static final short INTEGER = 0;
    public static final short FLOAT = 1;
    public static final short BOOLEAN = 2;
    public static final short LONG = 3;
    public static final short STRING = 4;
    public static final short STRING_SET = 5;


    public static final String KEY_STARTED = "started";
    public static final String KEY_GLOBALCONFIG = "globalConfig";
    public static final String KEY_WILDCONFIG = "wildConfig";
    public static final String KEY_USERINFO = "userInfo";

    /**
     * @param key
     * @param obj
     */
    public static void putValue(String key, Object obj) {
        SharedPreferences sharedPreferences = MyApp.getAppContext().getSharedPreferences("myshared", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (key != null) {
            if (obj instanceof Integer) {
                editor.putInt(key, (Integer) obj);
            } else if (obj instanceof Long) {
                editor.putLong(key, (Long) obj);
            } else if (obj instanceof Boolean) {
                editor.putBoolean(key, (Boolean) obj);
            } else if (obj instanceof Float) {
                editor.putFloat(key, (Float) obj);
            } else if (obj instanceof Set) {
                editor.putStringSet(key, (Set<String>) obj);
            } else if (obj instanceof String) {
                editor.putString(key, String.valueOf(obj));
            } else {//一个对象
                editor.putString(key, new Gson().toJson(obj));
            }
        }

        editor.commit();

    }

    /**
     * @param key
     * @param type 获取的数据类型
     * @return
     */

    public static Object getValue(String key, int type) {
        SharedPreferences preferences = MyApp.getAppContext().getSharedPreferences("myshared", Context.MODE_PRIVATE);
        switch (type) {
            case INTEGER:
                return preferences.getInt(key, -1);
            case FLOAT:
                return preferences.getFloat(key, -1f);
            case BOOLEAN:
                return preferences.getBoolean(key, false);
            case LONG:
                return preferences.getLong(key, -1L);
            case STRING:
                return preferences.getString(key, null);
            case STRING_SET:
                return preferences.getStringSet(key, null);
            default: // 默认取出String类型的数据
                return null;
        }
    }
}